<?php

namespace App\Models;

use App\Models\ActivityTeamUser;
//use App\Models\TeamBook;
use App\Services\Api\WorkService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\Models\ActivityClassBook;
use Illuminate\Support\Facades\Cache;
use App\Admin\Controllers\AdminApiController;

/**
 * App\Models\ActivityClassModel
 *
 * @property int $id
 * @property int $activity_id 活动ID
 * @property int $book_id 绑定的书本ID
 * @property int|null $sort_id 分类ID
 * @property string $class_name 活动名称
 * @property string|null $author 作者
 * @property string $book_name 书本名称
 * @property string $class_cove 活动封面
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\ActivityModel[] $activity
 * @property-read int|null $activity_count
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\BookModel[] $book
 * @property-read int|null $book_count
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereActivityId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereAuthor($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereBookId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereBookName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereClassCove($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereClassName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereSortId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\ActivityClassModel whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class ActivityClassModel extends Model
{
    //活动
    protected $table='activity_class';

    public function getClassCoveAttribute($value){
        return oss_domain().'/'.$value;
    }

    public function many_activity_class_book()
    {
        return $this->hasMany(ActivityClassBook::class, 'activity_class_id','id');
    }

    public function activity_class_book(){
        return $this->belongsToMany(BookModel::class, 'activity_class_book',
            'activity_class_id', 'book_id');
    }

    public function class_article(){

        return $this->belongsToMany(ArticleModel::class, 'activity_class_book',
            'activity_class_id', 'book_id');
    }

    //作业
    public function activity_class_work(){
        return $this->hasMany(ClassWorkModel::class, 'activity_class_id','id');
    }


    public function admin_class_article(){
        //return $this->hasMany(ActivityClassArticle::class,'class_id','id');
    }

    public function class_team(){
        return $this->belongsTo(ActivityTeamUser::class,'id','key_id');
    }

    public function class_work(){
        return $this->hasMany(ClassWorkModel::class,'activity_class_id','id');
    }

    public function activity_register(){
        return $this->hasOne(ActivityRegister::class,'activity_id','id');
    }

    public function class_info($class_id,$user_id){

     /*   $teamObj = ActivityTeamUser::where('user_id',$user_id)
            ->where('key_id',$class_id)
            ->where('team_type',2)
            ->with(['team'])
            ->first();

        if(empty($teamObj)){
            return [];
        }
        if(!empty($teamObj->wee_holiday)){
            $w = date("w");
            //$wee_holiday = explode(',',$teamObj->wee_holiday);
            $wee_holiday = $teamObj->wee_holiday;

            if(in_array($w,$wee_holiday) && $w!=0){

                return [];
            }elseif ($w==0 && in_array('7',$wee_holiday)){

                return [];
            }

            $sta = strtotime($teamObj->day_holiday_start);
            $end = strtotime($teamObj->day_holiday_end);
            if($sta >0 && $end>0){
                //dd($teamObj->id,$sta,$end);
                $now_time = time();
                if($now_time>=$sta && $now_time<=$end){
                    return [];
                }
            }

        }

       $total_days = app(WorkService::class)->get_total_work_date($teamObj->team->start_time,$teamObj->team->wee_holiday,$teamObj->team->day_holiday_start,$teamObj->team->day_holiday_end);

       $book = ActivityClassBook::where('activity_class_id',$class_id)
           ->with([
               'article'=>function($q){
                    $q->select(['id','article_title','book_id']);
               }
           ])
           ->orderBy('sort','asc')
           ->get()
           ->toArray();
        $article_number = 0;
       foreach ($book as $k=>$v){

           $article_number += count($v['article']);

           //排到那一本书
           if($article_number >= $total_days){
                $book_id = $v['book_id'];
                //計算该本书 排到第几章 不是第一本
                if($v['sort'] != 1){
                    $total_days = $total_days - count($v['article']);
                }
               break;
           }
       }

        $data =  $this->where('id',$class_id)
            ->select([
                'id',
                'class_name',
                'author',
                'class_cove',
                'start_time',
                'class_number',
            ])
            ->first();
        if(!empty($teamObj)){
            $data->class_team = $teamObj;
        }else{
            $data->class_team = '';
        }

        if(!empty($book_id)){
            $class_article = ArticleModel::where('book_id',$book_id)->select([
                'id',
                'order',
                'book_id',
                'article_title',
                'article_cover',
            ])
                ->orderBy('order','asc')
                ->take($total_days)
                ->get();
            $data->class_article = $class_article;

        }else{
            $data->class_article = '';
        }
        return $data;*/
    }

    public function class_list($user_id){

        $data = $this
            ->with([
                'class_team'=>function($q)use($user_id){
                    $q->where('user_id',$user_id)->select(['team_id','key_id','team_user_stash','created_at'])
                        ->where('team_type',2);
                },
            ])
            ->paginate(15)
            ->toArray();
        foreach ($data['data'] as $k=>$v){
            if(!empty($v['class_team'])){
                $data['data'][$k]['order'] = 1;
                //获取缓存
                $redis_key = env('REDIS_KEY_TEAM_WORK').$v['class_team']['team_id'];
                $work_data = Cache::get($redis_key);
                if(!empty($work_data)){
                    $work_data = json_decode($work_data,true);
                }else{
                    $api = new AdminApiController();
                    $res = $api->redis_team_book_article($v['class_team']['key_id'],2,$v['class_team']['team_id']);
                    $work_data = Cache::get($redis_key);
                    $work_data = json_decode($work_data,true);
                }
                $today = date("Y-m-d");
                if(!empty($work_data[$today])){
                    $data['data'][$k]['class_team']['read_book'] = $work_data[$today];
                }else{
                    $data['data'][$k]['class_team']['read_book'] = [];
                }
            }else{
                $data['data'][$k]['order'] = 0;
            }
        }
        $data['data'] = arraySort($data['data'], 'order');
        return $data;
    }

    public function class_list_array($company_id=0){

        $data =  $this
                //->where('company_id',$company_id)
                ->select([
                    'id',
                    'class_name as name',
                ])
                ->orderBy('created_at','desc')
                ->paginate(10)
                ->toArray();
        return $data;
    }

}
